<template>
  <view class="sign-in-container">
    <!-- 顶部标题 -->
    <view class="header">
      <text class="title">每日签到</text>
    </view>

    <!-- 签到卡片 -->
    <view class="sign-in-card">
      <view class="card-header">
        <text class="card-title">今日签到</text>
        <text class="sign-in-date">{{ currentDate }}</text>
      </view>
      
      <view class="sign-in-content">
        <view class="sign-in-button" @click="handleSignIn" :class="{ signed: hasSignedToday }">
          <text class="sign-in-text">{{ hasSignedToday ? '已签到' : '立即签到' }}</text>
        </view>
        
        <view class="reward-info">
          <text class="reward-text">签到奖励：{{ signInReward }} 积分</text>
        </view>
      </view>
    </view>

    <!-- 连续签到 -->
    <view class="continuous-sign-in">
      <text class="section-title">连续签到</text>
      <view class="continuous-days">
        <text class="days-text">已连续签到 {{ continuousDays }} 天</text>
        <view class="days-progress">
          <view class="progress-bar">
            <view class="progress-fill" :style="{ width: progressWidth + '%' }"></view>
          </view>
          <text class="progress-text">{{ continuousDays }}/7 天</text>
        </view>
      </view>
    </view>

    <!-- 签到记录 -->
    <view class="sign-in-record">
      <text class="section-title">本月签到记录</text>
      <view class="calendar">
        <view class="calendar-header">
          <text class="month-text">{{ currentMonth }}月</text>
        </view>
        <view class="calendar-grid">
          <view 
            v-for="day in calendarDays" 
            :key="day.date"
            class="calendar-day"
            :class="{ 
              'signed': day.signed,
              'today': day.isToday,
              'future': day.isFuture
            }"
          >
            <text class="day-number">{{ day.day }}</text>
            <view v-if="day.signed" class="signed-dot"></view>
          </view>
        </view>
      </view>
    </view>

    <!-- 签到规则 -->
    <view class="sign-in-rules">
      <text class="section-title">签到规则</text>
      <view class="rules-list">
        <view class="rule-item">
          <text class="rule-text">• 每日签到可获得 10 积分</text>
        </view>
        <view class="rule-item">
          <text class="rule-text">• 连续签到 7 天可获得额外 50 积分</text>
        </view>
        <view class="rule-item">
          <text class="rule-text">• 每月签到满 25 天可获得额外 100 积分</text>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import { store } from '@/uni_modules/uni-id-pages/common/store.js'

export default {
  data() {
    return {
      hasSignedToday: false,
      signInReward: 10,
      continuousDays: 0,
      currentDate: '',
      currentMonth: '',
      calendarDays: [],
      userScore: 0
    }
  },
  computed: {
    progressWidth() {
      return Math.min((this.continuousDays / 7) * 100, 100)
    },
    userInfo() {
      return store.userInfo
    },
    hasLogin() {
      return store.hasLogin
    }
  },
  onLoad() {
    this.initData()
    this.getUserScore()
    this.checkSignInStatus()
    this.generateCalendar()
  },
  methods: {
    initData() {
      const now = new Date()
      this.currentDate = now.toLocaleDateString('zh-CN', { 
        year: 'numeric', 
        month: 'long', 
        day: 'numeric' 
      })
      this.currentMonth = now.getMonth() + 1
    },
    
    async getUserScore() {
      if (!this.hasLogin) {
        this.userScore = 0
        return
      }
      
      try {
        const db = uniCloud.database()
        const res = await db.collection('uni-id-scores')
          .where('user_id == $env.uid')
          .field('balance')
          .orderBy('create_date', 'desc')
          .limit(1)
          .get()
        
        if (res.result.data && res.result.data.length > 0) {
          this.userScore = res.result.data[0].balance || 0
        } else {
          this.userScore = 0
        }
      } catch (error) {
        console.error('获取积分失败:', error)
        this.userScore = 0
      }
    },
    
    async checkSignInStatus() {
      if (!this.hasLogin) {
        this.hasSignedToday = false
        this.continuousDays = 0
        return
      }
      
      // 检查今日是否已签到
      try {
        const db = uniCloud.database()
        const today = new Date()
        const startOfDay = new Date(today.getFullYear(), today.getMonth(), today.getDate())
        const endOfDay = new Date(today.getFullYear(), today.getMonth(), today.getDate() + 1)
        
        const res = await db.collection('uni-id-scores')
          .where(`user_id == $env.uid && comment == "每日签到" && create_date >= $start && create_date < $end`)
          .get()
        
        this.hasSignedToday = res.result.data.length > 0
        
        // 获取连续签到天数
        await this.getContinuousDays()
      } catch (error) {
        console.error('检查签到状态失败:', error)
      }
    },
    
    async getContinuousDays() {
      if (!this.hasLogin) {
        this.continuousDays = 0
        return
      }
      
      try {
        const db = uniCloud.database()
        const res = await db.collection('uni-id-scores')
          .where(`user_id == $env.uid && comment == "每日签到"`)
          .orderBy('create_date', 'desc')
          .get()
        
        if (res.result.data.length === 0) {
          this.continuousDays = 0
          return
        }
        
        // 计算连续签到天数
        let continuous = 0
        const today = new Date()
        today.setHours(0, 0, 0, 0)
        
        for (let i = 0; i < res.result.data.length; i++) {
          const signInDate = new Date(res.result.data[i].create_date)
          signInDate.setHours(0, 0, 0, 0)
          
          const diffDays = Math.floor((today - signInDate) / (1000 * 60 * 60 * 24))
          
          if (diffDays === continuous) {
            continuous++
          } else {
            break
          }
        }
        
        this.continuousDays = continuous
      } catch (error) {
        console.error('获取连续签到天数失败:', error)
      }
    },
    
    generateCalendar() {
      const now = new Date()
      const year = now.getFullYear()
      const month = now.getMonth()
      const daysInMonth = new Date(year, month + 1, 0).getDate()
      const firstDay = new Date(year, month, 1).getDay()
      
      this.calendarDays = []
      
      // 填充上个月的日期
      for (let i = 0; i < firstDay; i++) {
        this.calendarDays.push({
          day: '',
          date: '',
          signed: false,
          isToday: false,
          isFuture: false
        })
      }
      
      // 填充当前月的日期
      for (let day = 1; day <= daysInMonth; day++) {
        const date = new Date(year, month, day)
        const isToday = date.toDateString() === now.toDateString()
        const isFuture = date > now
        
        this.calendarDays.push({
          day: day,
          date: date.toISOString().split('T')[0],
          signed: false, // 这里需要从数据库获取实际签到状态
          isToday: isToday,
          isFuture: isFuture
        })
      }
    },
    
    async handleSignIn() {
      if (this.hasSignedToday) {
        uni.showToast({
          title: '今日已签到',
          icon: 'none'
        })
        return
      }
      
      if (!this.hasLogin) {
        uni.showToast({
          title: '请先登录',
          icon: 'none'
        })
        return
      }
      
      try {
        uni.showLoading({
          title: '签到中...'
        })
        
        const db = uniCloud.database()
        
        // 添加积分记录
        await db.collection('uni-id-scores').add({
          user_id: this.userInfo._id,
          score: this.signInReward,
          type: 1, // 收入
          balance: this.userScore + this.signInReward,
          comment: '每日签到',
          create_date: new Date()
        })
        
        // 更新用户积分
        this.userScore += this.signInReward
        this.hasSignedToday = true
        this.continuousDays++
        
        // 检查连续签到奖励
        if (this.continuousDays === 7) {
          await this.addContinuousReward()
        }
        
        uni.hideLoading()
        uni.showToast({
          title: `签到成功！获得 ${this.signInReward} 积分`,
          icon: 'success'
        })
        
        // 刷新签到状态
        this.checkSignInStatus()
        this.generateCalendar()
        
      } catch (error) {
        uni.hideLoading()
        console.error('签到失败:', error)
        uni.showToast({
          title: '签到失败，请重试',
          icon: 'none'
        })
      }
    },
    
    async addContinuousReward() {
      try {
        const db = uniCloud.database()
        await db.collection('uni-id-scores').add({
          user_id: this.userInfo._id,
          score: 50,
          type: 1, // 收入
          balance: this.userScore + 50,
          comment: '连续签到7天奖励',
          create_date: new Date()
        })
        
        this.userScore += 50
        
        uni.showToast({
          title: '连续签到7天！获得额外50积分',
          icon: 'success'
        })
      } catch (error) {
        console.error('添加连续签到奖励失败:', error)
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.sign-in-container {
  background: #f5f8fc;
  min-height: 100vh;
  padding: 20rpx;
}

.header {
  text-align: center;
  padding: 40rpx 0;
}

.title {
  font-size: 36rpx;
  font-weight: bold;
  color: #222;
}

.sign-in-card {
  background: #fff;
  border-radius: 16rpx;
  padding: 32rpx;
  margin-bottom: 20rpx;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 32rpx;
}

.card-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #222;
}

.sign-in-date {
  font-size: 24rpx;
  color: #666;
}

.sign-in-content {
  text-align: center;
}

.sign-in-button {
  width: 200rpx;
  height: 80rpx;
  background: #007AFF;
  border-radius: 40rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 0 auto 24rpx;
  transition: all 0.3s;
}

.sign-in-button.signed {
  background: #ccc;
}

.sign-in-text {
  color: #fff;
  font-size: 28rpx;
  font-weight: bold;
}

.reward-info {
  margin-top: 16rpx;
}

.reward-text {
  font-size: 24rpx;
  color: #007AFF;
}

.continuous-sign-in {
  background: #fff;
  border-radius: 16rpx;
  padding: 32rpx;
  margin-bottom: 20rpx;
}

.section-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #222;
  margin-bottom: 24rpx;
  display: block;
}

.continuous-days {
  margin-bottom: 16rpx;
}

.days-text {
  font-size: 28rpx;
  color: #333;
  margin-bottom: 16rpx;
  display: block;
}

.days-progress {
  display: flex;
  align-items: center;
  gap: 16rpx;
}

.progress-bar {
  flex: 1;
  height: 16rpx;
  background: #f0f0f0;
  border-radius: 8rpx;
  overflow: hidden;
}

.progress-fill {
  height: 100%;
  background: #007AFF;
  transition: width 0.3s;
}

.progress-text {
  font-size: 24rpx;
  color: #666;
  min-width: 80rpx;
}

.sign-in-record {
  background: #fff;
  border-radius: 16rpx;
  padding: 32rpx;
  margin-bottom: 20rpx;
}

.calendar-header {
  text-align: center;
  margin-bottom: 24rpx;
}

.month-text {
  font-size: 28rpx;
  color: #333;
  font-weight: bold;
}

.calendar-grid {
  display: grid;
  grid-template-columns: repeat(7, 1fr);
  gap: 8rpx;
}

.calendar-day {
  aspect-ratio: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  border-radius: 8rpx;
  position: relative;
}

.calendar-day.signed {
  background: #007AFF;
}

.calendar-day.today {
  border: 2rpx solid #007AFF;
}

.calendar-day.future {
  opacity: 0.3;
}

.day-number {
  font-size: 24rpx;
  color: #333;
}

.calendar-day.signed .day-number {
  color: #fff;
}

.signed-dot {
  width: 8rpx;
  height: 8rpx;
  background: #fff;
  border-radius: 50%;
  position: absolute;
  bottom: 8rpx;
}

.sign-in-rules {
  background: #fff;
  border-radius: 16rpx;
  padding: 32rpx;
}

.rules-list {
  display: flex;
  flex-direction: column;
  gap: 16rpx;
}

.rule-item {
  display: flex;
  align-items: flex-start;
}

.rule-text {
  font-size: 26rpx;
  color: #666;
  line-height: 1.5;
}
</style> 